<template>
  <div class="p-6 space-y-4">
    <!-- 列表表格 -->
    <el-card shadow="never" class="rounded-lg">
      <div class="flex items-center justify-end mb-[10px]">
        <el-button v-if="!editWeight" type="primary" @click="onEdit">
          <svg-icon icon-class="edit-1" class="mr-2"></svg-icon>
          编辑
        </el-button>
        <template v-else>
          <el-button type="warning" @click="onCancelEdit">
            <svg-icon icon-class="cancel" class="mr-2"></svg-icon>
            取消
          </el-button>
          <el-button type="success" @click="onSave">
            <svg-icon icon-class="save" class="mr-2"></svg-icon>
            保存
          </el-button>
        </template>
      </div>
      <div v-loading="tableLoading">
        <el-table :data="tableData" height="80vh">
          <el-table-column label="序号" prop="index" width="80" align="center" />
          <el-table-column label="指标类型" prop="indexCategory" min-width="200" show-overflow-tooltip />
          <el-table-column label="权重" prop="weightValue" min-width="140">
            <template #header> 权重{{ totalValue }} </template>
            <template #default="{ row }">
              <div v-if="row.editWeight">
                <el-input v-model.number="row.weightValue" type="number" @input="verifyWeightValue($event, row)" placeholder="请输入权重" />
              </div>
              <div v-else>{{ row.weightValue }}</div>
            </template>
          </el-table-column>
          <el-table-column label="安全指数名称" prop="safetyIndex" min-width="160" />
          <el-table-column label="分类" prop="category" min-width="200" show-overflow-tooltip />
          <el-table-column label="" prop="subCategory" min-width="200" show-overflow-tooltip />
          <el-table-column label="风险赋值标准(每大类百分制扣分)" prop="deductionRule" min-width="300" show-overflow-tooltip />
          <el-table-column label="说明" prop="description" min-width="200" show-overflow-tooltip />
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getIndicatorList, updateIndicatorInfo } from '@/api/system/management/indicator';
import { cloneDeep } from 'lodash';
import { IndicatorListItem } from '@/api/system/management/indicator/types';

interface IndicatorRow {
  category: string;
  deductionRule: string;
  description: string;
  id: string;
  index?: number;
  indexCategory?: string;
  itemOrder?: number;
  managementId: string;
  safetyIndex?: string;
  subCategory: string;
  weightValue: string;
  editWeight: boolean;
}

const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
});

const tableData = ref<IndicatorRow[]>([]);
let copyTableData: IndicatorListItem[] = [];

const fetchList = async (triggerLoading = true) => {
  if (triggerLoading) queryLoading.value = true;
  tableLoading.value = true;
  try {
    await new Promise((r) => setTimeout(r, 200));
    const res = await getIndicatorList();
    if (res.data && res.data?.length > 0) {
      const filtered = [];
      let index = 0;
      res.data.forEach((item) => {
        index++;
        const categoryObj = {};
        item.indexManagementDetailList.forEach((dItem, dIndex) => {
          if (dIndex === 0) {
            categoryObj[dItem.category] = dItem.category;
            filtered.push({
              index,
              ...dItem,
              ...item
            });
          } else {
            const haveCategory = categoryObj[dItem.category];
            categoryObj[dItem.category] = dItem.category;
            if (haveCategory) {
              filtered.push({
                ...dItem,
                category: ''
              });
            } else {
              filtered.push({
                ...dItem
              });
            }
          }
        });
      });
      tableData.value = filtered;
      copyTableData = cloneDeep(res.data);
    }
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const editWeight = ref(false);
const onEdit = () => {
  setEditWeight(true);
};
const onCancelEdit = () => {
  setEditWeight(false);
  fetchList();
};

const totalValue = computed(() => {
  let totalValue = 0;
  // 校验数据
  tableData.value.forEach((item) => {
    if (item.weightValue && item.weightValue !== '修正系数') {
      totalValue += Number(item.weightValue);
    }
  });
  return Number.isNaN(totalValue) ? '' : totalValue;
});

const onSave = () => {
  const weightValueObj = {};
  // 校验数据
  tableData.value.forEach((item) => {
    if (item.weightValue) {
      weightValueObj[item.id] = item.weightValue;
    }
  });
  copyTableData.forEach((item) => {
    item.weightValue = weightValueObj[item.id];
  });
  if (Number(totalValue.value) === 100) {
    updateIndicatorInfo(copyTableData)
      .then(() => {
        ElMessage.success('数据修改成功');
      })
      .catch((e) => {
        console.error(e);
      })
      .finally(() => {
        fetchList();
        setEditWeight(false);
      });
  } else if (Number(totalValue.value) < 100) {
    ElMessage.warning('权重总和小于100，请进行修正');
  } else if (Number(totalValue.value) > 100) {
    ElMessage.warning('权重总和大于100，请进行修正');
  } else {
    ElMessage.error('数据异常!');
  }
};

const verifyWeightValue = (value, row) => {
  let numValue;
  // 处理空值
  if (value === null || value === undefined) {
    numValue = 0;
  }
  // 处理字符串
  else if (isNaN(value)) {
    numValue = 0;
  }
  // 处理数字（包括小数）
  else {
    // 转换为数字并四舍五入取整
    numValue = Math.round(Number(value));

    // 检查范围
    if (numValue < 0) {
      numValue = 0;
    } else if (numValue > 100) {
      numValue = 100;
    }
  }
  row.weightValue = numValue;
};

// 设置编辑状态
const setEditWeight = (flag: boolean) => {
  tableData.value.forEach((item) => {
    if (item.weightValue) {
      item.editWeight = flag;
    }
  });
  editWeight.value = flag;
};

onMounted(async () => {
  await fetchList(false);
});
</script>
